from datetime import datetime
from django.shortcuts import render
from django.views import View
from django.core.cache import cache
from django.http import HttpResponse
from backend.models import User
from frontend.models import UserAndGoods
from spider.main import GoodsSpider
from frontend.models import Goods
import json,os,random
from PriceCompare import settings
from backend.utils import DailyStatisticsAdd
from backend.utils import KeyWordRecord
from backend.utils import updateCookies
from django.shortcuts import redirect 
# Create your views here.
class Index(View):
    """
    返回主页
    """
    def get(self,request):
        return render(request,'index.html')

class ToSearchPage(View):
    """
    从主页跳转到搜索页
    """
    def get(self,request):
        key = request.GET.get('key','衣服')
        return render(request,'search.html',{'djangoKey':key})

class Search(View):
    """
    搜索比价
    """
    def get(self,request):
        key = request.GET.get('key',None)
        page = int(request.GET.get('page',1))
        orderby = request.GET.get('orderby','')
        cache_key = f"{key}_{page}_{orderby}"
        print(cache_key)
        if key:
            # 统计每日搜索
            DailyStatisticsAdd('search')
            # 统计关键字词频
            KeyWordRecord(key)
            data = cache.get(cache_key, default=None)
            if not data:
                pdata = GoodsSpider().run(key,page,orderby)
                pt = pdata['curPage']
                pageNum = pdata['pageNum']
                malls = pdata["malls"]
                goods = pt.to_dict(orient = 'records')
                data={}
                data['pageNum'] = pageNum
                data['malls'] = malls
                data['goods'] = goods
                cache.set(cache_key, data, timeout=120)
                for good in goods:
                    try:
                        goods = Goods.objects.create(
                            link=good['detail_link'],
                            price=good['price'],
                            name=good['title'],
                            pic_url=good['pic'],
                            mall=good['mall'],
                            store=good['store']
                        )
                    except Exception as e :
                        print(e)
            
            print(data)
            return HttpResponse(json.dumps(data))

def handleDetailPage(request):
    """
    处理商品详情页
    """
    redict = request.GET.get('redict',None)
    cookie = request.COOKIES
    login = cookie.get('login',None)
    phone = cookie.get('phone',None)
    
    url = request.get_raw_uri()
    redict=redict.replace('@','&')
    print('redict',redict)
    print('phone',phone)
    print('url',url)
    if login and phone and User.objects.filter(phone=phone):
        # 用户已登录
        user = User.objects.get(phone=phone)
        # print('user',user.name)
        goods = Goods.objects.get(link=url)
        # print('goods',goods.link)
        UserAndGoods.objects.create(
            user=user,
            goods=goods,
            relation='浏览'
        )
    if redict[:4] == 'http' :
        return redirect(redict)
    else:
        return redirect('http://s.manmanbuy.com'+redict)
    

def initImage(request):
    """
    返回初始头像
    参数:
        index:1-10 不带参数则返回随机头像
    """
    index = request.GET.get('index',None)
    reset = request.GET.get('reset',None)
    if reset: # 重置头像
        cookie = request.COOKIES
        phone = cookie.get('phone',None)
        if User.objects.filter(phone=phone):
            user = User.objects.get(phone=phone)
            image = '/randomImage/?index='+str(random.randint(1,10))
            user.image = image
            user.save()
            return updateCookies(HttpResponse(json.dumps({'url':image})),image=image)
    file_name = os.path.join(settings.BASE_DIR,'static_files','images','random',f'd-{index if index else random.randint(1,10)}.jpg')
    with open(file_name,'rb') as f: img = f.read()
    return HttpResponse(img,content_type='image/jpg')

def initBackendPage(request):
    """
    后端页面初始化
    """
    cookie = request.COOKIES
    login = cookie.get('login',None)
    image = cookie.get('image',None)
    name = cookie.get('name',None)
    authority = cookie.get('authority',None)
    print(login,image,name,authority)
    if not login : return redirect('/static/login.html')
    if login == 'user':
        option={
        "homeInfo": {
            "title": "个人主页",
            "href": "/static/page/userinfo.html"
        },
        "logoInfo": {
            "title": name,
            "image": image if image else '/randomImage',
            "href": '#',
            "href": "/static/page/homePage.html"
        },
        "menuInfo": [{
            "title": "用户菜单",
            "icon": "fa fa-address-book",
            "href": "",
            "target": "_self",
            "child": [{
                    "title": "前往首页",
                    "href": "/static/index.html",
                    "icon": "fa fa-tachometer",
                    "target": "_blank"
                },
                {
                    "title": "基本资料",
                    "href": "/static/page/userinfo.html",
                    "icon": "fa fa-tachometer",
                    "target": "_self"
                },
                {
                    "title": "修改密码",
                    "href": "/static/page/alterpwd.html",
                    "icon": "fa fa-gears",
                    "target": "_self"
                },
                {
                    "title": "积分",
                    "href": "/static/page/score.html",
                    "icon": "fa fa-gears",
                    "target": "_self",
                },
                {
                    "title": "浏览记录",
                    "href": "/static/page/userhistory.html",
                    "icon": "fa fa-arrow-up",
                    "target": "_self"
                },
                {
                    "title": "收藏夹",
                    "href": "/static/page/usercollection.html",
                    "icon": "fa fa-arrow-up",
                    "target": "_self"
                },
                {
                    "title": "消息中心",
                    "href": "/static/page/usermessage.html",
                    "icon": "fa fa-arrow-up",
                    "target": "_self"
                }
            ]
        }]
    }
    elif login == 'admin':
        option={
            "homeInfo": {
                "title": "全局概览",
                "href": "/static/page/homePage.html"
            },
            "logoInfo": {
                "title": name,
                "image": "/randomImage",
                "href": image if image else '/randomImage',
                "href": "/static/page/homePage.html"
            },
            "menuInfo": [{
                "title": "统计图表",
                "icon": "fa fa-address-book",
                "href": "",
                "target": "_self",
                "child": [{
                        "title": "搜索统计",
                        "href": "/static/page/echarts_search.html",
                        "icon": "fa fa-tachometer",
                        "target": "_self"
                    },
                    {
                        "title": "用户统计",
                        "href": "/static/page/echarts_user.html",
                        "icon": "fa fa-gears",
                        "target": "_self"
                    },
                    {
                        "title": "评论统计",
                        "href": "/static/page/echarts_comment.html",
                        "icon": "fa fa-arrow-up",
                        "target": "_self"
                    },
                    {
                        "title": "收藏统计",
                        "href": "/static/page/echarts_collection.html",
                        "icon": "fa fa-arrow-up",
                        "target": "_self"
                    },
                    {
                        "title": "商品统计",
                        "href": "/static/page/echarts_goods.html",
                        "icon": "fa fa-arrow-up",
                        "target": "_self"
                    },
                    {
                        "title": "收益统计",
                        "href": "graph_rickshaw.html",
                        "icon": "fa fa-arrow-up",
                        "target": "_self"
                    }
                ]
            }]
        }
        if authority == '0' :
            option['menuInfo'].append({
                "title": "管理",
                "icon": "fa fa-address-book",
                "href": "",
                "target": "_self",
                "child": [{
                        "title": "评论审核",
                        "href": "graph_rickshaw.html",
                        "icon": "fa fa-arrow-up",
                        "target": "_self"
                    },
                    {
                        "title": "用户管理",
                        "href": "graph_rickshaw.html",
                        "icon": "fa fa-arrow-up",
                        "target": "_self"
                    }
                ]
            })
    
    
    return HttpResponse(json.dumps(option))

def imageUpload(request):
    """
    图片上传(修改个人头像专用)
    """
    if request.method == 'POST':
        cookie = request.COOKIES
        login = cookie.get('login',None)
        phone = cookie.get('phone',None)
        if not login or not phone : return redirect('/static/login.html')
        image = None
        try:
            image = request.FILES.get('file')
            imgtype = image.name.split('.')[-1]
            name = str(datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))+'.'+imgtype
            print('name=',name)
            upload_root=os.path.join(settings.BASE_DIR,'static_files','upload')
            if not os.path.exists(upload_root): os.mkdir(upload_root)
            with open(os.path.join(upload_root,name),'wb') as f:
                f.write(image.read())
            url = '/static/upload/'+name
            # 为用户更新头像
            if  User.objects.filter(phone=phone):
                user = User.objects.get(phone=phone)
                user.image=url
                user.save()
                image = url
            else:
                err = f'{phone} 该用户不存在'
                code=1
                raise Exception(err)
            err = ''
            code = 0
        except Exception as e:
            print(e)
            err = str(e)
            code = 1
        finally:
            resp = HttpResponse(json.dumps({'code':code,'url':url,'err':err}))
            # 更新cookie
            resp = updateCookies(resp,image=image)
            return resp


        
    

